<template>
  <el-card class="edit-fac">
    <router-link to="/sensor/node/manager">
      <el-button type="primary">返回设备列表</el-button>
    </router-link>

    <el-button type="success" class="save-edit" @click="handleSave"
      >保存</el-button
    >
    <el-button type="danger" class="save-edit" @click="handleDelete"
      >删除</el-button
    >
    <el-tabs tab-position="left" class="demo-tabs">
      <el-tab-pane label="设备详情">
        <el-form
          ref="ruleForm"
          class="demo-form-inline"
          :model="nodeObj"
          :inline="true"
          size="default"
          :rules="rules"
        >
          <el-form-item label="设备名称" prop="type">
            <el-select
              v-model="nodeObj.type"
              placeholder="please select"
              clearable
            >
              <el-option
                v-for="(fac, index) in facNameList"
                :key="index"
                :label="fac"
                :value="fac"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="nodeCreateTime">
            <el-date-picker
              v-model="nodeObj.nodeCreateTime"
              type="datetime"
              placeholder="Select date and time"
            />
          </el-form-item>
          <el-form-item label="mac地址" prop="mac">
            <el-input v-model="nodeObj.mac" placeholder="mac地址" />
          </el-form-item>
          <el-form-item label="经纬度" prop="address">
            <el-input v-model="nodeObj.address" placeholder="经纬度">
              <template #append
                ><a href="https://lbs.amap.com/tools/picker" target="_blank"
                  >picker</a
                ></template
              >
            </el-input>
          </el-form-item>

          <el-form-item label="上报间隔" prop="reportInterval">
            <el-input v-model="nodeObj.reportInterval" placeholder="上报间隔" />
          </el-form-item>

          <el-form-item label="上行LQI" prop="upLqi">
            <el-input v-model="nodeObj.upLqi" placeholder="上行LQI" />
          </el-form-item>
          <el-form-item label="下行LQI" prop="downLqi">
            <el-input v-model="nodeObj.downLqi" placeholder="下行LQI" />
          </el-form-item>

          <el-form-item label="设备状态" prop="status">
            <!-- <template #default="{ row }"> -->
            <el-tag
              type="success"
              size="default"
              effect="dark"
              v-if="nodeObj.status === 1"
              >正常
            </el-tag>
            <el-tag type="info" size="default" effect="dark" v-else>
              异常
            </el-tag>
            <!-- </template> -->
          </el-form-item>
          <el-form-item>
            <el-upload
              class="avatar-uploader"
              action="/api/fmms/systemController/uploadAvatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-tooltip
                class="box-item"
                :effect="$store.getters.themeStatus ? 'light' : 'customized'"
                content="Add Or Modify"
                placement="top"
              >
                <img
                  v-if="nodeObj.picPath"
                  :src="nodeObj.picPath"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-tooltip>
            </el-upload>
          </el-form-item>
        </el-form>
        <!-- vue2 -->
        <!--   <el-image-viewer
          v-if="showViewer"
          :url-list="imageList"
          @close="closeImageList"
        /> -->
      </el-tab-pane>
      <el-tab-pane label="设备状态">
        <el-table class="sesor-table" :data="currentNodeResource" border>
          <el-table-column type="index" label="ID" align="center" width="100" />
          <el-table-column property="name" label="名称" align="center" />
          <el-table-column property="value" label="值" align="center" />
          <el-table-column property="status" label="读/写" align="center">
            <template #default="{ row }">
              <el-tag
                :type="row.status === 0 ? 'success' : 'danger'"
                effect="dark"
                >{{ row.status === 0 ? '读' : '写' }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            property="updateTime"
            label="更新时间"
            align="center"
          />
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="实时图">
        <div>
          <graph />
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import {
  addOrUpdateNodeListById,
  getFacilityNameList,
  getNodeListById,
  getNodeResourceList,
  deleteFacilityById
} from '@/api/facility.js'
import { ElMessage } from 'element-plus'
import { updateCurrentFacilityInfo } from '@/api/facility.js'
// const showViewer = ref(false)
/* const closeImageList = () => {
  showViewer.value = false
} */

// const imageUrl = ref('')

const ruleForm = ref(null)

const facNameList = ref([])

const initNodeObj = () => {
  return {
    mac: '',
    address: '',
    downLqi: '',
    reportInterval: '',
    type: '',
    upLqi: '',
    nodeCreateTime: '',
    status: 1,
    id: '',
    picPath: ''
  }
}

const rules = ref({
  mac: [{ required: true, message: '请输入', trigger: 'blur' }],
  address: [{ required: true, message: '请输入', trigger: 'blur' }],
  downLqi: [
    { required: true, message: '请输入', trigger: 'blur' },
    { min: 1, max: 3, message: '长度在 1 到 3 个字符', trigger: 'blur' }
  ],
  reportInterval: [{ required: true, message: '请输入', trigger: 'blur' }],
  type: [{ required: true, message: '请选择', trigger: 'blur' }],
  upLqi: [
    { required: true, message: '请输入', trigger: 'blur' },
    { min: 1, max: 3, message: '长度在 1 到 3 个字符', trigger: 'blur' }
  ],
  nodeCreateTime: [{ required: true, message: '请输入', trigger: 'blur' }],
  status: [{ required: true, message: '请输入', trigger: 'blur' }]
})

const nodeObj = ref(initNodeObj())

const getNodeObj = async () => {
  if (Boolean(route.query.id)) {
    try {
      // console.log(Boolean(route.query.id))
      const res = await getNodeListById(route.query.id)
      // console.log(res)
      nodeObj.value = res.data
    } catch (error) {
      ElMessage.error(error)
    }
  } else {
    return false
  }
}

// 增加 或 更新
const addOrEdit = () => {
  ruleForm.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (Boolean(route.query.id)) {
          res = await addOrUpdateNodeListById(nodeObj.value, route.query.id)
          ElMessage({
            type: 'success',
            duration: 1500,
            message: '更新成功'
          })
        } else {
          res = await addOrUpdateNodeListById(nodeObj.value, 0)
          ElMessage({
            type: 'success',
            duration: 1500,
            message: '添加成功'
          })
        }
      } catch (error) {
        ElMessage({
          type: 'success',
          duration: 1500,
          message: '更新/添加失败'
        })
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}

// 获取设备名称列表
const initFacilityNameList = async () => {
  try {
    const res = await getFacilityNameList('facility')
    // console.log(res)
    facNameList.value = res.data
  } catch (error) {
    ElMessage.error(error)
  }
}

const currentNodeResource = ref([])

const handleCurrentResourceById = async () => {
  if (Boolean(route.query.mac)) {
    try {
      const res = await getNodeResourceList(route.query.mac)
      // console.log(res)
      currentNodeResource.value = res.data
    } catch (error) {
      ElMessage.error(error)
    }
  } else {
    return false
  }
}

const route = useRoute()
onMounted(() => {
  initFacilityNameList()
  getNodeObj()
  handleCurrentResourceById()
})

const handleSave = () => {
  addOrEdit()
}
const handleDelete = async () => {
  if (Boolean(router.query.id)) {
    try {
      const res = await deleteFacilityById(router.query.id)
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          duration: 1500,
          message: '删除成功'
        })
      }
    } catch (error) {
      ElMessage.error(error)
    }
  }
}

const handleAvatarSuccess = async (res, uploadFile) => {
  // console.log(res)
  if (res.code === 200) {
    nodeObj.value.picPath = res.data

    if (Boolean(route.query.id)) {
      try {
        // 存储图片path
        await updateCurrentFacilityInfo(
          { imageUrl: nodeObj.value.picPath },
          route.query.id
        )
        ElMessage({
          type: 'success',
          duration: 1500,
          message: '图片更新成功'
        })
      } catch (error) {
        ElMessage({
          type: 'error',
          duration: 1500,
          message: error
        })
      }
    } else {
      ElMessage({
        type: 'success',
        duration: 1500,
        message: '图片上传成功'
      })
    }
  } else {
    ElMessage({
      type: 'error',
      duration: 1500,
      message: '图片上传失败'
    })
  }
}

const imgType = ref(['imag/jpeg', 'image/png'])
const beforeAvatarUpload = (mutipartFile) => {
  const imgStatus = imgType.value.includes(mutipartFile.type)
  // console.log(imgType.value.includes(mutipartFile.type))
  const isLt2M = mutipartFile.size / 1024 / 1024 < 2
  if (!imgStatus) {
    ElMessage.error('上传头像图片只能是 JPEG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return imgStatus && isLt2M
}
</script>
<style scoped>
/* .el-popper.is-customized {
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
} */
</style>
<style scoped>
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: #409eff;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
<style lang="scss" scoped>
:global(.el-popper.is-customized) {
  padding: 5px 8px;
}
.el-row {
  margin: 10px 0px;
  padding: 10px;
}
.avatar-uploader .avatar {
  width: 160px;
  height: 160px;
  display: block;
}
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.edit-fac {
  // height: 556px;
  .el-form .el-form-item:not(:last-child) {
    margin-bottom: 33px;
  }
  .el-form-item:last-child {
    padding: 8px 0px;
  }
  & .el-button {
    margin-bottom: 15px;
  }
}
:deep(.el-form--inline .el-form-item) {
  width: 380px;
}
.save-edit {
  margin-left: 15px;
}
</style>
